(function () {
  const showMsgEle = document.getElementById("show-msg");
  const inputMsgEle = document.getElementById("input-msg-ele");
  const sendMsgBtn = document.getElementById("send-msg-btn");

  // navigator.serviceWorker 只有在https或localhost下才可见
  // 在file协议下也是可见的,可是不工作
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("./util.sw.js").then(function () {
      console.log("Service Worker 注册成功");
    });
    navigator.serviceWorker.addEventListener("message", function (e) {
      if (document.title === e.data.from) {
        return;
      }
      showMsgEle.value = e.data.msg;
    });
  }

  sendMsgBtn.addEventListener("click", function () {
    // 这里navigator.serviceWorker.controller初始值是null,除非刷新页面
    navigator.serviceWorker.controller.postMessage({
      from: document.title,
      msg: inputMsgEle.value,
    });
  });
})();
